<template>
    <div class="divShow">
        <el-row>
            <el-col :span="24">
                <div style="padding: 30px;">
                    <!-- 搜索框 -->
                    <el-form :inline="true" :model="searchProduct" class="demo-form-inline" v-if="showSearch">
                        <el-form-item label="物料编码">
                            <el-input v-model="searchProduct.itemCode" placeholder="请输入物料编码"></el-input>
                        </el-form-item>
                        <el-form-item label="物料名称">
                            <el-input v-model="searchProduct.itemName" placeholder="请输入物料名称"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="checkMdItem">查询</el-button>
                            <el-button @click="cleanMdItem">重置</el-button>
                        </el-form-item>
                    </el-form>


                    <el-row>
                        <el-col :span="22">
                            <!-- 按钮 -->
                            <el-button type="primary" size="small" @click="changeDialog(null)">新增</el-button>
                            <el-button type="success" size="small" :disabled="!judgmentCh"
                                @click="changeDialog(SelMdItemId)">修改</el-button>
                            <el-button type="danger" size="small" :disabled="!judgmentDe"
                                @click="delJudg">删除</el-button>
                            <el-button type="info" size="small">导入</el-button>
                            <el-button type="warning" size="small" @click="exportExcel">导出</el-button>
                        </el-col>
                        <el-col :span="2">
                            <div>
                                <el-tooltip content="隐藏搜索" placement="top">
                                    <el-button icon="el-icon-search" circle @click="toggleSearch"></el-button>
                                </el-tooltip>
                                <el-tooltip content="刷新" placement="top">
                                    <el-button icon="el-icon-refresh" circle @click="refresh"></el-button>
                                </el-tooltip>
                            </div>
                        </el-col>
                    </el-row>
                    <!-- 表格 -->
                    <el-table :data="productTable" ref="productTable" style="width: 100%;"
                        @selection-change="handleSelectionChange">

                        <el-table-column type="selection" width="55">
                        </el-table-column>

                        <el-table-column prop="itemId" label="产品物料ID" v-if="false">
                        </el-table-column>
                        <el-table-column prop="itemCode" label="物料编码">
                        </el-table-column>
                        <el-table-column prop="itemName" label="物料名称">
                        </el-table-column>
                        <el-table-column prop="specification" label="规格型号">
                        </el-table-column>
                        <el-table-column prop="unitOfMeasure" label="单位">
                        </el-table-column>
                        <el-table-column prop="itemOrProduct" label="物料/产品" width="100">
                        </el-table-column>
                        <el-table-column prop="itemTypeName" label="所属分类">
                        </el-table-column>
                        <el-table-column prop="enableFlag" label="是否启用">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.enableFlag === 'Y'">是</el-tag>
                                <el-tag v-else type="danger">否</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="safeStockFlag" label="设置安全库存" width="120">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.safeStockFlag === 'Y'">是</el-tag>
                                <el-tag v-else type="danger">否</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="创建时间" width="180">
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-col :span="12">
                                    <el-link type="primary" @click="changeDialog(scope.row.itemId)">修改</el-link>
                                </el-col>
                                <el-col :span="12">
                                    <el-link type="primary" @click="delDialog(scope.row.itemId)">删除</el-link>
                                </el-col>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页模块 -->
                    <el-pagination :page-size="searchProduct.pageSize" :total="searchProduct.total"
                        @current-change="searchProductChange" layout="prev, pager, next">
                    </el-pagination>

                    <!-- dialog -->
                    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="60%" class="rounded-dialog"
                        :close-on-click-modal="false" @close="closeMdItemDialog">
                        <el-form :model="AddMdItem" ref="mdItemForm" :rules="rules" style="padding-left:50px;">

                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="物料编码" prop="itemCode">
                                        <el-input v-model="AddMdItem.itemCode" autocomplete="off" style="width: 180px;"
                                            placeholder="请输入物料编码"></el-input>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="12">
                                    <el-form-item label="物料名称" prop="itemName">
                                        <el-input v-model="AddMdItem.itemName" autocomplete="off" style="width: 180px;"
                                            placeholder="请输入物料名称"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-form-item label="规格型号" prop="specification">
                                <el-input v-model="AddMdItem.specification" type="textarea" :rows="2" autocomplete="off"
                                    style="width: 620px;" placeholder="请输入规格型号"></el-input>
                            </el-form-item>
                            <el-row>
                                <el-col :span="8">
                                    <el-form-item label="单位" prop="unitOfMeasure">
                                        <el-input v-model="AddMdItem.unitOfMeasure" autocomplete="off"
                                            style="width: 144px;"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="16">
                                    <el-form-item label="物料/产品分类" prop="itemOrProduct">
                                        <el-input v-model="AddMdItem.itemOrProduct" autocomplete="off"
                                            style="width: 144px;"></el-input>

                                        <el-checkbox v-model="AddMdItem.highValue">高价值/易被盗物品</el-checkbox>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col>
                                    <el-form-item label="是否启用" prop="enableFlag">
                                        <el-radio v-model="AddMdItem.enableFlag" label="Y">是</el-radio>
                                        <el-radio v-model="AddMdItem.enableFlag" label="N">否</el-radio>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="批次管理" prop="batchFlag">
                                        <el-switch v-model="AddMdItem.batchFlag" active-text="是" inactive-text="否"
                                            active-value="Y" inactive-value="N"></el-switch>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="安全库存" prop="safeStockFlag">
                                        <el-radio v-model="AddMdItem.safeStockFlag" label="Y">是</el-radio>
                                        <el-radio v-model="AddMdItem.safeStockFlag" label="N">否</el-radio>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row style="padding-top: 20px;">
                                <el-col :span="24">
                                    <el-form-item label="备注" prop="remark">
                                        <el-input v-model="AddMdItem.remark" type="textarea" :rows="2"
                                            autocomplete="off" style="width: 640px;" placeholder="请输入备注"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="closeMdItemDialog">取 消</el-button>
                            <el-button type="primary" @click="submitForm('mdItemForm')">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>
            </el-col>
        </el-row>

    </div>
</template>
<script>
import axios from 'axios';
import qs from 'qs';
import * as XLSX from 'xlsx'; // 使用命名导入
import FileSaver from 'file-saver';
import excelExport from '../../utils/excel-export';
export default {
    data() {
        return {
            // 设置dialog默认不显示
            dialogFormVisible: false,
            //根据是否有id输入判断标题
            dialogTitle: '',
            // 分页查询数据
            searchProduct: {
                itemCode: '',
                itemName: '',
                ItemTypeName: '',
                pageSize: 5,
                pageNo: 1,
                total: 0,
            },
            // 查询显示表格
            productTable: [],
            //新增MdItem或者修改MdItem
            AddMdItem: {
                itemId: '',
                itemCode: '',
                itemName: '',
                specification: '',
                unitOfMeasure: '',
                itemOrProduct: '',
                highValue: '',
                enableFlag: '',
                batchFlag: '',
                safeStockFlag: '',
                remark: '',
                token: '',
            },
            columns: [
                'itemCode',
                'itemName',
                'specification',
                'unitOfMeasure',
                'itemOrProduct',
                'highValue',
                'enableFlag',
                'batchFlag',
                'safeStockFlag',
                'remark'
            ],
            // 验证规则
            rules: {
                itemCode: [
                    { required: true, message: '请输入物料编码', trigger: 'blur' }
                ],
                itemName: [
                    { required: true, message: '请输入物料名称', trigger: 'blur' }
                ],
                specification: [
                    { required: true, message: '请输入规格型号', trigger: 'blur' }
                ],
                unitOfMeasure: [
                    { required: true, message: '请输入单位', trigger: 'blur' }
                ],
                itemOrProduct: [
                    { required: true, message: '请输入物料/产品分类', trigger: 'blur' }
                ],
                enableFlag: [
                    { required: true, message: '请选择是否启用', trigger: 'change' }
                ],
                batchFlag: [
                    { required: true, message: '请选择批次管理', trigger: 'change' }
                ],
                safeStockFlag: [
                    { required: true, message: '请选择安全库存', trigger: 'change' }
                ],
                remark: [
                    { required: false, message: '请输入备注', trigger: 'blur' }
                ]
            },
            selectedRows: [],
            judgmentCh: false,
            judgmentDe: false,
            //当前选中行的MdItemId的数组
            arrayMdItemId: [],
            // 获取当前选中行的MdItemId
            SelMdItemId: '',
            showSearch: true, // 控制搜索框的显示和隐藏
        }
    },

    mounted() {
        this.checkListMdItem();
        console.log('XLSX:', XLSX); // 检查XLSX是否已正确定义
    },
    methods: {
        //导出为excel文件
        exportExcel() {
            excelExport(this.$refs.productTable.columns, this.productTable, this.formatJson, "产品物料信息.xlsx");
        },

        formatJson(columns, jsonData) {
            // 防御性编程，确保 jsonData 是数组
            if (!Array.isArray(jsonData)) {
                return [];
            }

            return jsonData.map(row => columns.map(col => {
                const value = row[col.prop];
                if (['enableFlag', 'safeStockFlag'].includes(col.prop)) {
                    return value === 'Y' ? '是' : '否';
                } else if (col.prop === 'createTime') {
                    return new Date(value).toLocaleString(); // 假设 createTime 是日期时间格式
                } else {
                    return value;
                }
            }));
        },
        //刷新按钮
        refresh() {
            location.reload();
        },
        //是否显示搜索框
        toggleSearch() {
            // 切换搜索框的显示和隐藏
            this.showSearch = !this.showSearch;
        },
        //删除判断
        delJudg() {
            if (this.selectedRows.length === 1) {
                //删除单个id
                console.log(this.SelMdItemId);
                this.delDialog(this.SelMdItemId)
            } else {
                //删除多个id
                console.log(this.arrayMdItemId);
                this.$confirm("确定要删除" + this.arrayMdItemId + " 这" + this.arrayMdItemId.length + "条数据吗？", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.delMdItemIdArray(this.arrayMdItemId)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        //获取当前选中表格行的状态
        handleSelectionChange(selection) {
            this.selectedRows = selection;

            // 更新 arrayMdItemId
            this.arrayMdItemId = selection.map(row => row.itemId);
            if (selection.length === 1) {
                //获取单个id
                this.SelMdItemId = this.selectedRows[0].itemId
                console.log(this.SelMdItemId);

                this.judgmentDe = true;
                this.judgmentCh = true;
            } else if (selection.length > 1) {
                //获取一组id
                let rowsLength = this.selectedRows.length
                for (let index = 0; index < rowsLength; index++) {
                    this.arrayMdItemId[index] = this.selectedRows[index].itemId;
                }
                this.judgmentCh = false;
                this.judgmentDe = true;
            } else {
                this.judgmentCh = false;
                this.judgmentDe = false;
            }
        },
        //根据传递进来的MdItemId数组来进行批量删除
        delMdItemIdArray(arrayMdItemId) {


            this.$axios.delete("http://localhost:9970/emsSystem/api/MdItem/delMdItemArray", { data: arrayMdItemId }).then((res) => {
                if (res.data.code === 200) {
                    //删除成功
                    this.$message.success("删除成功");
                    this.checkListMdItem();
                }
            })
        }
        ,
        //根据id删除指定数据
        delDialog(mdItemId) {
            this.$confirm('确定要删除该条信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.delete("http://localhost:9970/emsSystem/api/MdItem/delMdItem/" + mdItemId).then((res) => {
                    if (res.data.code === 200) {
                        //删除成功
                        this.$message.success("删除成功");
                        this.checkListMdItem();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //关闭dialog并且清空里面的数据
        closeMdItemDialog() {
            this.$refs.mdItemForm.resetFields();
            this.AddMdItem.itemId = "",
                this.AddMdItem.highValue = "",
                this.dialogFormVisible = false
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 表单验证通过，执行提交操作
                    this.AddOrChMdItem();
                } else {
                    console.log('表单验证失败');
                    return false;
                }
            });
        },
        //添加或者修改MdItem
        AddOrChMdItem() {

            //获取存在前端的token
            let dlyk_token = localStorage.getItem('dlyk_token');
            this.AddMdItem.token = dlyk_token


            //转化类型
            this.AddMdItem.highValue = this.AddMdItem.highValue ? 'Y' : 'N';

            let qsMdItem = qs.stringify(this.AddMdItem);
            console.log(qs);

            this.$axios.post("http://localhost:9970/emsSystem/api/MdItem/AddOrChMdItem", qsMdItem).then((res) => {
                if (res.data.code === 200) {
                    //修改成功
                    this.$message.success("修改或新增成功");
                    this.dialogFormVisible = false;
                    this.checkListMdItem();
                }
            })
        },
        //改变dialog标题显示
        changeDialog(id) {
            this.dialogFormVisible = true
            if (id == null) {
                this.dialogTitle = "新增物料/产品"
            } else {
                console.log(id);
                this.dialogTitle = "修改物料/产品"
                this.AddMdItem.itemId = id
                this.checkMdItemById(id);
            }

        },
        //根据mdItemId查询数据
        checkMdItemById(mdItemId) {
            this.$axios.post("http://localhost:9970/emsSystem/api/MdItem/CheckMdItemById/" + mdItemId).then((res) => {
                if (res.data.code === 200) {
                    this.AddMdItem = res.data.data
                    if (res.data.data.highValue === "Y") {
                        this.AddMdItem.highValue = true;
                    }
                }
            })
        },
        // 改变页码
        searchProductChange(value) {
            this.searchProduct.pageNo = value;
            this.checkListMdItem();

        },
        // 进行条件搜索
        checkMdItem() {
            this.checkListMdItem();
        },
        // 清空搜索框
        cleanMdItem() {
            this.searchProduct.itemCode = ""
            this.searchProduct.itemName = ""
        },
        // 查询MdItem数据方法
        checkListMdItem() {

            let qsStr = qs.stringify(this.searchProduct);


            this.$axios.post("http://localhost:9970/emsSystem/api/MdItem/checkListMdItem", qsStr).then((res) => {
                if (res.data.code === 200) {
                    this.productTable = res.data.data.records
                    console.log(this.productTable)
                    this.searchProduct.pageNo = res.data.data.current
                    this.searchProduct.pageSize = res.data.data.size
                    this.searchProduct.total = res.data.data.total
                }
            })
        }
    }
}
</script>
<style>
.divShow {
    background-color: white;
    border-radius: 10px;
}

.rounded-dialog .el-dialog {
    border-radius: 10px;
    /* 设置圆角 */
}
</style>
